package com.example.pungolo.journal;

import java.io.File;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;

public class U {
  private U() { }
  public static final long MS_IN_A_DAY = 86400000;

  public static int dayFromDate(Date date) {
    // ad esempio, io sono gmt+1 (italia), quindi offset sar� 3600000 (un'ora)
    // se da me sono le 18, a gmt sono le 17
    // devo incrementare timestamp di offset per ottenere l'inizio della giornata alla mia timezone
    Calendar c = Calendar.getInstance();
    c.setTime(date);
    c.set(Calendar.HOUR, 0);
    c.set(Calendar.MINUTE, 0);
    c.set(Calendar.SECOND, 0);
    c.set(Calendar.MILLISECOND, 0);
    long timestamp = c.getTimeInMillis();
    long offset = TimeZone.getDefault().getOffset(timestamp);
    long day = (timestamp + offset) / MS_IN_A_DAY; // ms in un giorno*/
    return (int)day;
  }
  
  public static Date dateFromDay(int day) {
    return new Date(tsOfDayStart(day));
  }
  
  public static long tsOfDayStart(int day) {
    long timestamp = day * MS_IN_A_DAY;
    long offset = TimeZone.getDefault().getOffset(timestamp);
    long newtimestamp = timestamp - offset;
    long newoffset = TimeZone.getDefault().getOffset(newtimestamp);
    if (newoffset == offset)
      return newtimestamp;
    else
      return timestamp - newtimestamp;
  }

  public static int today() {
    return dayFromDate(new Date());
  }
  
  public static <T> int indexOf(T[] array, T searched) {
    for (int i = 0; i < array.length; i++)
      if ((array[i] == null && searched == null) || (array[i] != null && array[i].equals(searched)))
        return i;
    return -1;
  }

  public static boolean delete(String imagePath) {
    if (imagePath == null)
      return false;
    File file = new File(imagePath);
    if (file.exists())
      return file.delete();
    return false;
  }

  public static boolean exists(String imagePath) {
    if (imagePath == null)
      return false;
    File file = new File(imagePath);
      return file.exists();
  }
}
